<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;

class Weixinpay {

    // 设置参数
// 商户号
    public $merchantId = '';
// 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
    public $merchantPrivateKeyFilePath = '';
    public $merchantPrivateKeyInstance = "";
// 「商户API证书」的「证书序列号」
    public $merchantCertificateSerial = '3775B6A45ACD588826D15E583A95F5DD********';
// 从本地文件中加载「微信支付平台证书」，可由内置CLI工具下载到，用来验证微信支付应答的签名
    public $platformCertificateFilePath = 'file:///path/to/wechatpay/certificate.pem';
    public $onePlatformPublicKeyInstance = "";
// 「微信支付平台证书」的「平台证书序列号」
// 可以从「微信支付平台证书」文件解析，也可以在 商户平台 -> 账户中心 -> API安全 查询到
    public $platformCertificateSerial = '7132D72A03E93CDDF8C03BBD1F37EEDF********';
// 从本地文件中加载「微信支付公钥」，用来验证微信支付应答的签名
    public $platformPublicKeyFilePath = 'file:///path/to/wechatpay/publickey.pem';
    public $twoPlatformPublicKeyInstance = "";
// 「微信支付公钥」的「微信支付公钥ID」
// 需要在 商户平台 -> 账户中心 -> API安全 查询
    public $platformPublicKeyId = 'PUB_KEY_ID_01142321349124100000000000********';

// 构造一个 APIv3 客户端实例


    public static function createClient() {

        $config = config_item("weixin_pay");
        
        $merchantId = $config["merchantId"];
        
        $merchantCertificateSerial = $config["api_zhengshu_xuliehao"];
        $merchantPrivateKeyFilePath = $config["apiclient_key"];
        $merchantPrivateKeyFilePath = file_get_contents($merchantPrivateKeyFilePath);
        //echo $merchantPrivateKeyFilePath;
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
        
        $platformPublicKeyId = $config["public_key_id"];
        $platformPublicKeyFilePath = $config["pubic_key"];
        $platformPublicKeyFilePath = file_get_contents($config["pubic_key"]);
        $twoPlatformPublicKeyInstance = Rsa::from($platformPublicKeyFilePath, Rsa::KEY_TYPE_PUBLIC);
        

        $onePlatformPublicKeyInstance = "asdsd";
        $platformCertificateSerial = "asdfadsf";

        $param = [
            'mchid' => $merchantId,
            'serial' => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs' => [
                //$platformCertificateSerial => $onePlatformPublicKeyInstance,
                $platformCertificateSerial => $twoPlatformPublicKeyInstance,
                $platformPublicKeyId => $twoPlatformPublicKeyInstance,
            ],
        ];
        print_r($param);

        $instance = Builder::factory($param);
        return $instance;
    }

    public static function native() {
        try {
            $instance = self::createClient();

            $resp = $instance
                    ->chain('v3/pay/transactions/native')
                    ->post(['json' => [
                    'mchid' => '1900006XXX',
                    'out_trade_no' => 'native12177525012014070332333',
                    'appid' => 'wxdace645e0bc2cXXX',
                    'description' => 'Image形象店-深圳腾大-QQ公仔',
                    'notify_url' => 'https://weixin.qq.com/',
                    'amount' => [
                        'total' => 1,
                        'currency' => 'CNY'
                    ],
            ]]);

            echo $resp->getStatusCode(), PHP_EOL;
            echo (string) $resp->getBody(), PHP_EOL;
        } catch (\Exception $e) {
            // 进行错误处理
            echo $e->getMessage(), PHP_EOL;
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                $r = $e->getResponse();
                echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
                echo (string) $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
            }
            echo $e->getTraceAsString(), PHP_EOL;
        }
    }

    public static function first() {
        // 发送请求
        try {
            
            $instance = self::createClient();
            
            $resp = $instance->chain('v3/certificates')->get(
                    /** @see https://docs.guzzlephp.org/en/stable/request-options.html#debug */
                    // ['debug' => true] // 调试模式
            );
            echo (string) $resp->getBody(), PHP_EOL;
        } catch (\Exception $e) {
            // 进行异常捕获并进行错误判断处理
            echo $e->getMessage(), PHP_EOL;
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                $r = $e->getResponse();
                echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
                echo (string) $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
            }
            echo $e->getTraceAsString(), PHP_EOL;
        }
    }

}
